import { Component,useEffect,useState } from 'react'
import { View, Text,Input,Icon,Swiper,SwiperItem,Image, Button,Textarea,Picker } from '@tarojs/components'
import './index.less'
import { connect } from 'react-redux'
import { getSort,setSort as setBlogSort } from '../../api/sort'
import { CreateBlog } from '../../api/blog' 
import Taro from '@tarojs/taro'
import { create } from '../../actions/user'

function Create (props){
  const [title,setTitle] = useState('')
  const [content,setContent] = useState('')
  const [sort,setSort] = useState([])
  const [sort_name,setSort_name] = useState([])
  const [sort_id,setSort_id] = useState('')

  const push = () => {
    if(title=='')Taro.showToast({title:'请输入标题',icon:'none'})
    else if(content=='')Taro.showToast({title:'请输入正文',icon:'none'})
    else if(sort_id=='')Taro.showToast({title:'请选择分类',icon:'none'})

    else CreateBlog(title,content,props.data.user_id).then(res=>{
      if(res.data.code == 200){
        setBlogSort(sort_id,res.data.data.blog_id).then(res => {
          if(res.data.code == 200){
            props.update(true)
            Taro.switchTab({ url: '/pages/index/index' })
            Taro.navigateTo({ url: '/pages/detail/index?blog_id='+res.data.data.blog_id })
            Taro.showToast({
              title: '创建成功',
              icon: 'success',
              duration: 2000
            })
            setTitle('')
            setContent('')
            document.getElementsByClassName('picker')[0].innerHTML = '分类:'
          }
        })
      }
    })

  }

  const getSortList = () => {
    getSort().then(res => {
      let selector= []
      res.data.data.map(item =>{
        selector.push(item.sort_name)
      })
      setSort(selector)
      selector= []
      res.data.data.map(item =>{
        selector.push(item.sort_name)
      })
      setSort_name(selector)
    })
  }

  useEffect(()=>{
    getSortList()
  },[])
  
  return (
    <View className='create'>
        <Input type='text' placeholder='请输入标题' value={title} onInput={e=>setTitle(e.detail.value)}/>
        <Button onClick={push}>发布</Button>
        <View className='page-section'>
          <View className='sort'>
            <Picker mode='selector' range={sort} onChange={(e)=>{
              setSort_id(e.detail.value)
              document.getElementsByClassName('picker')[0].innerHTML = '分类:'+ sort_name[e.detail.value]
              }}>
              <View className='picker'>
                分类 : 
              </View>
            </Picker>
          </View>
        </View>
        <Textarea placeholder='请输入内容' maxlength='-1' value={content} onInput={e=>setContent(e.detail.value)}></Textarea>
    </View>
  )
}

const hoc = connect(({ login }) => ({
  data:login
}), (dispatch) => ({
  update(data){
    dispatch(create(data))
  }
}))

export default hoc(Create)